//
// Created by haoy on 2017/6/20.
//

#include <sstream>

#include "rtp/rtp_header.hpp"
#include "xcutil.h"

RtpHeader::RtpHeader() {}

int RtpHeader::read(const uint8_t *data, const int size) {
    if (size < 12) {
        return 0;
    }
    uint8_t first_byte = data[0];
    v = first_byte >> 6 & 0x3;
    p = first_byte >> 5 & 0x1;
    x = first_byte >> 4 & 0x1;
    cc = first_byte & 0xF;
    uint8_t second_byte = data[1];
    m = second_byte >> 7 & 0x1;
    pt = second_byte & 0x7F;
    seq = be_get_u16(data + 2);
    ts = be_get_u32(data + 4);
    ssrc = be_get_u32(data + 8);

    return 12;
}

int RtpHeader::write(uint8_t *data, const int size) {
    if (size < this->size()) {
        return 0;
    }
    //cc = csrcs.size();
    data[0] = v << 6 | p << 5 | x << 4 | cc;
    data[1] = m << 7 | pt;
    be_set_u16(seq, data + 2);
    be_set_u32(ts, data + 4);
    be_set_u32(ssrc, data + 8);

    return 12;
}

int RtpHeader::size() const {
    return 12;
}